package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.MyPage;
import com.nowcoder.community.entity.PageEntity;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.impl.FollowServiceImpl;
import com.nowcoder.community.service.impl.UserServiceImpl;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author cjh
 * @date 2023/1/12 - 18:36
 */
@Controller
public class FollowController implements CommunityConstant {
    @Autowired
    FollowServiceImpl followService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    HostHolder hostHolder;
    @Autowired
    private EventProducer eventProducer;

    @RequestMapping(path = "/follow", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public String follow(int entityType, int entityId) {
        User user = hostHolder.getUser();
        followService.follow(user.getId(), entityType, entityId);

//        储发关注事件
        Event event = new Event()
                .setTopic(TOPIC_FOLLOW)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(entityType)
                .setEntityId(entityId)
                .setEntityUserId(entityId);

//        因为是关注 不需要连接到对应帖子
        eventProducer.fireEvent(event);


        return CommunityUtil.getJsonString(0, "已关注");
    }

    @RequestMapping(path = "/unfollow", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public String unfollow(int entityType, int entityId) {
        User user = hostHolder.getUser();
        followService.unfollow(user.getId(), entityType, entityId);
        return CommunityUtil.getJsonString(0, "已取消关注");
    }

    @RequestMapping(path = "/followees/{userId}", method = RequestMethod.GET)
    public String getFollowees(@PathVariable("userId") int userId, PageEntity pageEntity, Model model) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        model.addAttribute("user", user);

        pageEntity.setSize(5);
        MyPage myPage = new MyPage();
        myPage.setCurrent((int) pageEntity.getCurrent());
        myPage.setSize((int) pageEntity.getSize());
        myPage.setTotal((int) followService.findFolloweeCount(userId, CommunityConstant.ENTITY_TYPE_User));

        List<Map<String, Object>> userList = followService.findFollowees(userId, pageEntity);
        if (userList != null) {
            for (Map<String, Object> map : userList) {
                User u = (User) map.get("user");
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }

        model.addAttribute("users", userList);
//        需要封装的内容
        model.addAttribute("page", myPage);
        long from = myPage.getCurrent() - 2;
        from = from < 1 ? 1 : from;
        long to = myPage.getCurrent() + 2;
        to = Math.min(to, myPage.getPages());
        model.addAttribute("from", from);
        model.addAttribute("to", to);
        model.addAttribute("path", "/followees/" + userId);
        return "/site/followee";
    }


    @RequestMapping(path = "/followers/{userId}", method = RequestMethod.GET)
    public String getFollowers(@PathVariable("userId") int userId, PageEntity pageEntity, Model model) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        model.addAttribute("user", user);

        pageEntity.setSize(5);
        MyPage myPage = new MyPage();
        myPage.setCurrent((int) pageEntity.getCurrent());
        myPage.setSize((int) pageEntity.getSize());
        myPage.setTotal((int) followService.findFollowerCount(CommunityConstant.ENTITY_TYPE_User, userId));

        List<Map<String, Object>> userList = followService.findFollowers(userId, pageEntity);
        if (userList != null) {
            for (Map<String, Object> map : userList) {
                User u = (User) map.get("user");
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }

        model.addAttribute("users", userList);
//        需要封装的内容
        model.addAttribute("page", myPage);
        long from = myPage.getCurrent() - 2;
        from = from < 1 ? 1 : from;
        long to = myPage.getCurrent() + 2;
        to = Math.min(to, myPage.getPages());
        model.addAttribute("from", from);
        model.addAttribute("to", to);
        model.addAttribute("path", "/followers/" + userId);
        return "/site/follower";
    }

    private boolean hasFollowed(int userId) {
        if (hostHolder.getUser() == null) {
            return false;
        }
        return followService.hasFollowed(hostHolder.getUser().getId(), CommunityConstant.ENTITY_TYPE_User, userId);
    }


}
